<template>
	<view class="order-container">
		<!-- 顶部标签页 -->
		<view class="tabs">
			<u-tabs :list="tabList" :current="currentTab" @change="changeTab" scrollable="false"></u-tabs>
		</view>

		<!-- 销售和进货模块 -->
		<template v-if="currentTab === 0 || currentTab === 1">
			<!-- 单据类型按钮 -->
			<view class="doc-type-buttons">
				<template v-if="currentTab === 0">
					<button class="doc-button" :class="{ active: docType === 'sales' }"
						@click="changeDocType('sales')">出货</button>
					<button class="doc-button" :class="{ active: docType === 'return' }"
						@click="changeDocType('return')">退货</button>
					<button class="doc-button" :class="{ active: docType === 'payment' }"
						@click="changeDocType('payment')">收款</button>
				</template>
				<template v-else-if="currentTab === 1">
					<button class="doc-button" :class="{ active: docType === 'purchase' }"
						@click="changeDocType('purchase')">进货</button>
					<button class="doc-button" :class="{ active: docType === 'return' }"
						@click="changeDocType('return')">退货</button>
					<button class="doc-button" :class="{ active: docType === 'payment' }"
						@click="changeDocType('payment')">付款</button>
				</template>
			</view>

			<!-- === 完整表单 (销售-出/退货 或 进货-进货/退货) === -->
			<template
				v-if="(currentTab === 0 && (docType === 'sales' || docType === 'return')) || (currentTab === 1 && (docType === 'purchase' || docType === 'return'))">
				<!-- 时间和客户/供应商选择 (Bind to currentState) -->
				<view class="info-section">
					<view class="info-item">
						<view class="info-icon"><u-icon name="clock" size="20" color="#666666"></u-icon></view>
						<text class="info-label">时间</text>
						<view class="info-value" @click="showDatePicker = true">{{ selectedDate }}</view>
						<!-- Date is global -->
					</view>
					<view class="info-item">
						<view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
						<text class="info-label">{{ currentTab === 0 ? '客户' : '供应商' }}</text>
						<view class="info-value" @click="selectPartner">{{ currentState.selectedPartner || (currentTab
							=== 0 ? '请选择客户' : '请选择供应商') }}</view>
					</view>
				</view>

				<!-- 已选择商品区域 (Bind to currentState) -->
				<view class="selected-goods-section">
					<view class="selected-goods-header">
						<text class="selected-text">选中货品 ({{ currentState.selectedGoodsCount }})</text>
						<text class="total-text">合计金额: ¥{{ currentState.totalAmount.toFixed(2) }}</text>
					</view>

					<view class="selected-goods-list" v-if="currentState.selectedGoodsList.length > 0">
						<u-swipe-action>
							<u-swipe-action-item
								v-for="(item, index) in currentState.selectedGoodsList"
								:key="index"
								:options="swipeOptions"
								@click="(e) => handleSwipeClick(e, index)"
							>
								<view class="selected-goods-item">
									<view class="selected-goods-image">
										<image :src="item.goodImage || '/static/images/default-goods.png'" mode="aspectFill">
										</image>
									</view>
									<view class="selected-goods-info">
										<view class="selected-goods-name">{{ item.name }}</view>
										<view class="selected-goods-price-row">
											<text class="selected-goods-price">单价：¥{{ item.price }}</text>
										</view>
										<view class="selected-goods-bottom">
											<view class="quantity-control">
												<text class="btn-minus" @click.stop="decreaseQuantity(index)">-</text>
												<input type="number" class="quantity-input" v-model="item.quantity" @blur="updateQuantity(index)" />
												<text class="btn-plus" @click.stop="increaseQuantity(index)">+</text>
											</view>
											<view class="selected-goods-amount">金额：¥{{ (item.quantity *
												parseFloat(item.price)).toFixed(2) }}</view>
										</view>
									</view>
								</view>
							</u-swipe-action-item>
						</u-swipe-action>
					</view>

					<view class="empty-goods" v-else>
						<u-empty mode="car" :text="emptyText"></u-empty>
					</view>

					<view class="add-goods-btn" @click="addGoods">
						<u-icon name="plus" size="40" color="#39C9BB"></u-icon>
					</view>
				</view>

				<template v-if="currentState.selectedGoodsList.length > 0">
					<view class="settlement-section">
						<view class="settlement-item">
							<text class="settlement-label">折扣率</text>
							<view class="discount-input-container">
								<input type="digit" class="discount-input" :value="currentState.discountRate"
									@input="onDiscountRateInput" placeholder="100" />
								<text class="percent-sign">%</text>
							</view>
						</view>
						<view class="settlement-item">
							<text class="settlement-label">折后金额</text>
							<text class="settlement-value">{{ currentState.discountAmount.toFixed(2) }}</text>
						</view>

						<!-- 恢复原始的本单实收和结算账户代码 -->
						<view class="settlement-item">
							<text class="settlement-label">本单实收</text>
							<input type="digit" class="actual-amount-input" :value="currentState.actualAmount"
								@input="onActualAmountInput" placeholder="请输入实收金额" />
						</view>
						<view class="settlement-item">
							<text class="settlement-label">结算账户</text>
							<view class="settlement-value-select" @click="selectAccount">
								<text>{{ currentState.selectedAccount }}</text>
								<u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
							</view>
						</view>
					</view>

					<view class="remark-section">
						<text class="remark-label">备注 (最多输入200个字)</text>
						<textarea class="remark-input" :value="currentState.remark" @input="handleRemarkInput"
							placeholder="请输入备注内容" maxlength="200"></textarea>
						<view class="remark-btootm"></view>
					</view>

					<view class="footer-actions">
						<view class="btn-again" hover-class="btn-again-hover" @click="recordAgain">再记一笔</view>
						<view class="btn-save" hover-class="btn-save-hover" @click="saveRecord(true)">保存</view>
					</view>
				</template>
			</template>

			<!-- === 简化表单 (销售-收款) === -->
			<template v-if="currentTab === 0 && docType === 'payment'">
				<!-- 时间和客户选择 -->
				<view class="info-section">
					<view class="info-item">
						<view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
						<text class="info-label">客户</text>
						<view class="info-value" @click="selectPartner">{{ salesPaymentState.selectedPartner || '请选择客户' }}</view>
					</view>
				</view>

				<!-- 收款金额部分替换为多账户支付方式 -->
				<view class="settlement-section">
					<view class="payment-methods">
						<view class="payment-method-item">
							<text class="payment-method-name">现金</text>
							<input type="digit" class="payment-method-input" v-model="salesPaymentState.cashAmount" 
								@input="updateSalesPaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">银行存款</text>
							<input type="digit" class="payment-method-input" v-model="salesPaymentState.bankAmount" 
								@input="updateSalesPaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">微信</text>
							<input type="digit" class="payment-method-input" v-model="salesPaymentState.wechatAmount" 
								@input="updateSalesPaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">支付宝</text>
							<input type="digit" class="payment-method-input" v-model="salesPaymentState.alipayAmount" 
								@input="updateSalesPaymentAmount" placeholder="0.00" />
						</view>
					</view>
					<view class="payment-total">
						<text class="payment-total-label"></text>
						<text class="payment-total-value">{{ salesPaymentState.paymentAmount.toFixed(2) }}</text>
					</view>
				</view>

				<!-- 备注区域 -->
				<view class="remark-section">
					<text class="remark-label">备注 (最多输入200个字)</text>
					<textarea class="remark-input" v-model="salesPaymentState.remark" placeholder="请输入备注内容" maxlength="200"></textarea>
					<view class="remark-btootm"></view>
				</view>

				<!-- 底部按钮 (收款专用) -->
				<view class="footer-actions">
					<view class="btn-again" hover-class="btn-again-hover" @click="recordAgain">再记一笔</view>
					<view class="btn-save" hover-class="btn-save-hover" @click="saveRecord(true)">保存收款</view>
				</view>
			</template>

			<!-- === 简化表单 (进货-付款) === -->
			<template v-if="currentTab === 1 && docType === 'payment'">
				<!-- 时间和供应商选择 -->
				<view class="info-section">
					<view class="info-item">
						<view class="info-icon"><u-icon name="account" size="20" color="#666666"></u-icon></view>
						<text class="info-label">供应商</text>
						<view class="info-value" @click="selectPartner">{{ purchasePaymentState.selectedPartner || '请选择供应商' }}</view>
					</view>
				</view>

				<!-- 付款金额部分替换为多账户支付方式 -->
				<view class="settlement-section">
					<view class="payment-methods">
						<view class="payment-method-item">
							<text class="payment-method-name">现金</text>
							<input type="digit" class="payment-method-input" v-model="purchasePaymentState.cashAmount" 
								@input="updatePurchasePaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">银行存款</text>
							<input type="digit" class="payment-method-input" v-model="purchasePaymentState.bankAmount" 
								@input="updatePurchasePaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">微信</text>
							<input type="digit" class="payment-method-input" v-model="purchasePaymentState.wechatAmount" 
								@input="updatePurchasePaymentAmount" placeholder="0.00" />
						</view>
						<view class="payment-method-item">
							<text class="payment-method-name">支付宝</text>
							<input type="digit" class="payment-method-input" v-model="purchasePaymentState.alipayAmount" 
								@input="updatePurchasePaymentAmount" placeholder="0.00" />
						</view>
					</view>
					<view class="payment-total">
						<text class="payment-total-label"></text>
						<text class="payment-total-value">{{ purchasePaymentState.paymentAmount.toFixed(2) }}</text>
					</view>
				</view>

				<!-- 备注区域 -->
				<view class="remark-section">
					<text class="remark-label">备注 (最多输入200个字)</text>
					<textarea class="remark-input" :value="purchasePaymentState.remark"
						@input="purchasePaymentState.remark = $event.detail.value" placeholder="请输入备注内容"
						maxlength="200"></textarea>
					<view class="remark-btootm"></view>
				</view>

				<!-- 底部按钮 (付款专用) -->
				<view class="footer-actions">
					<view class="btn-again" hover-class="btn-again-hover" @click="recordAgain">再记一笔</view>
					<view class="btn-save" hover-class="btn-save-hover" @click="saveRecord(true)">保存付款</view>
				</view>
			</template>

		</template>

		<!-- 其他收入模块 -->
		<template v-if="currentTab === 2">
			<!-- 顶部信息展示 -->
			<view class="income-header">
				<view class="header-title">
					<text>经营所得</text>
					<text class="amount">{{ totalAmount.toFixed(2) }}</text>
				</view>
			</view>

			<!-- 收入类型选择 -->
			<view class="income-types">
				<!-- 第一行 -->
				<view class="type-row">
					<view class="type-item" :class="{ 'active': incomeType === 'business' }"
						@click="selectIncomeType('business')">
						<view class="icon-wrapper blue">
							<u-icon name="home" size="24" color="#fff"></u-icon>
						</view>
						<text>经营所得</text>
					</view>
					<view class="type-item" :class="{ 'active': incomeType === 'sales' }"
						@click="selectIncomeType('sales')">
						<view class="icon-wrapper red">
							<u-icon name="shopping-cart" size="24" color="#fff"></u-icon>
						</view>
						<text>销售收入</text>
					</view>
					<view class="type-item" :class="{ 'active': incomeType === 'interest' }"
						@click="selectIncomeType('interest')">
						<view class="icon-wrapper orange">
							<u-icon name="rmb-circle" size="24" color="#fff"></u-icon>
						</view>
						<text>利息收入</text>
					</view>
				</view>
				<!-- 第二行 -->
				<view class="type-row">
					<view class="type-item" :class="{ 'active': incomeType === 'investment' }"
						@click="selectIncomeType('investment')">
						<view class="icon-wrapper yellow">
							<u-icon name="arrow-upward" size="24" color="#fff"></u-icon>
						</view>
						<text>投资收入</text>
					</view>
					<view class="type-item" :class="{ 'active': incomeType === 'salary' }"
						@click="selectIncomeType('salary')">
						<view class="icon-wrapper green">
							<u-icon name="bag" size="24" color="#fff"></u-icon>
						</view>
						<text>工资</text>
					</view>
					<view class="type-item" :class="{ 'active': incomeType === 'other' }"
						@click="selectIncomeType('other')">
						<view class="icon-wrapper purple">
							<u-icon name="plus" size="24" color="#fff"></u-icon>
						</view>
						<text>其它</text>
					</view>
				</view>
			</view>
		</template>

		<!-- 其他支出模块 -->
		<template v-if="currentTab === 3">
			<!-- 顶部信息展示 -->
			<view class="expense-header">
				<view class="header-title">
					<text>经营支出</text>
					<text class="amount">{{ totalAmount.toFixed(2) }}</text>
				</view>
			</view>

			<!-- 支出类型选择 -->
			<view class="expense-types">
				<!-- 第一行 -->
				<view class="type-row">
					<view class="type-item" :class="{ 'active': expenseType === 'business' }"
						@click="selectExpenseType('business')">
						<view class="icon-wrapper blue">
							<u-icon name="home" size="24" color="#fff"></u-icon>
						</view>
						<text>经营支出</text>
					</view>
					<view class="type-item" :class="{ 'active': expenseType === 'purchase' }"
						@click="selectExpenseType('purchase')">
						<view class="icon-wrapper red">
							<u-icon name="shopping-cart" size="24" color="#fff"></u-icon>
						</view>
						<text>采购支出</text>
					</view>
					<view class="type-item" :class="{ 'active': expenseType === 'tax' }"
						@click="selectExpenseType('tax')">
						<view class="icon-wrapper orange">
							<u-icon name="file-text" size="24" color="#fff"></u-icon>
						</view>
						<text>税费支出</text>
					</view>
				</view>
				<!-- 第二行 -->
				<view class="type-row">
					<view class="type-item" :class="{ 'active': expenseType === 'rent' }"
						@click="selectExpenseType('rent')">
						<view class="icon-wrapper yellow">
							<u-icon name="home-fill" size="24" color="#fff"></u-icon>
						</view>
						<text>房租水电</text>
					</view>
					<view class="type-item" :class="{ 'active': expenseType === 'salary' }"
						@click="selectExpenseType('salary')">
						<view class="icon-wrapper green">
							<u-icon name="account" size="24" color="#fff"></u-icon>
						</view>
						<text>工资支出</text>
					</view>
					<view class="type-item" :class="{ 'active': expenseType === 'other' }"
						@click="selectExpenseType('other')">
						<view class="icon-wrapper purple">
							<u-icon name="plus" size="24" color="#fff"></u-icon>
						</view>
						<text>其它</text>
					</view>
				</view>
			</view>
		</template>

		<!-- 共用的账户和备注部分（其他收入和支出） -->
		<template v-if="currentTab >= 2">
			<view class="form-section">
				<u-cell-group :border="false">
					<u-cell title="往来单位" :value="selectedPartner || '请选择'" isLink @click="selectPartner">
						<u-icon slot="icon" name="account" size="20" customStyle="margin-right: 10rpx;"></u-icon>
					</u-cell>
					<u-cell title="结算账户" :value="selectedAccount || '现金'" isLink @click="selectAccount">
						<u-icon slot="icon" name="rmb" size="20" customStyle="margin-right: 10rpx;"></u-icon>
					</u-cell>
				</u-cell-group>
			</view>

			<view class="remark-section">
				<view class="remark-title">备注（最多输入200个字）</view>
				<textarea class="remark-textarea" placeholder="请输入备注内容" maxlength="200" v-model="remark"></textarea>
				<!-- <view class="date-display">{{ selectedDate }}</view> -->
				<view class="remark-btootm">
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="footer-actions" v-if="currentTab >= 2">
				<view class="btn-again" hover-class="btn-again-hover" @click="recordAgain">再记一笔</view>
				<view class="btn-save" hover-class="btn-save-hover" @click="saveRecord(true)">保存</view>
			</view>
		</template>

		<!-- 日期时间选择器 -->
		<u-datetime-picker :show="showDatePicker" v-model="currentDate" mode="date" @confirm="confirmDate"
			@cancel="showDatePicker = false"></u-datetime-picker>

		<!-- 往来单位选择器 -->
		<u-picker :show="showPartnerPicker" :columns="[partnerColumns]" keyName="label" @confirm="confirmPartner"
			@cancel="cancelPicker"></u-picker>

		<!-- 结算账户选择器 -->
		<u-picker :show="showAccountPicker" :columns="[accountColumns]" keyName="label" @confirm="confirmAccount"
			@cancel="cancelPicker"></u-picker>

	</view>
</template>

<script>
import api from '@/utils/api.js'
import request from '@/utils/http.js'

export default {
	data() {
		return {
			tabList: [
				{ name: '销售' },
				{ name: '进货' },
				// { name: '其他收入' },
				// { name: '其他支出' }
			],

			currentTab: 0,
			docType: 'sales', // Default docType for sales tab
			showDatePicker: false,
			currentDate: Number(new Date()),
			selectedDate: new Date().toISOString().split('T')[0],
			
			// 添加滑动操作的选项
			swipeOptions: [
				{
					text: '删除',
					style: {
						backgroundColor: '#fa3534'
					}
				}
			],

			// --- State Objects --- 
			salesState: {
				docType: 'sales',
				selectedPartner: null,
				selectedPartnerId: null,
				selectedAccount: '现金',
				selectedGoodsCount: 0,
				selectedGoodsList: [],
				totalAmount: 0,
				discountRate: 100.00,
				discountAmount: 0,
				actualAmount: 0,
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: '',
			},
			returnState: {
				docType: 'return',
				selectedPartner: null,
				selectedPartnerId: null,
				selectedAccount: '现金',
				selectedGoodsCount: 0,
				selectedGoodsList: [],
				totalAmount: 0,
				discountRate: 100.00,
				discountAmount: 0,
				actualAmount: 0,
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: '',
			},
			purchaseOrderState: { // Purchase Order
				docType: 'purchase',
				selectedPartner: '', // 供应商名称
				selectedPartnerId: null, // 供应商ID(supplierId)
				selectedAccount: '现金',
				selectedGoodsCount: 0,
				selectedGoodsList: [],
				totalAmount: 0,
				discountRate: 100.00,
				discountAmount: 0,
				actualAmount: 0,
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: '',
			},
			purchaseReturnState: { // Purchase Return
				docType: 'return', // Match the button value
				selectedPartner: '', // 供应商名称
				selectedPartnerId: null, // 供应商ID(supplierId)
				selectedAccount: '现金',
				selectedGoodsCount: 0,
				selectedGoodsList: [],
				totalAmount: 0,
				discountRate: 100.00,
				discountAmount: 0,
				actualAmount: 0,
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: '',
			},
			purchasePaymentState: { // Purchase Payment
				docType: 'payment', // Match the button value
				selectedPartner: '', // 供应商名称
				selectedPartnerId: null, // 供应商ID(supplierId)
				selectedAccount: '现金',
				paymentAmount: 0, // 总支付金额
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: ''
			},
			// 新增销售收款状态对象
			salesPaymentState: { // Sales Payment
				docType: 'payment',
				selectedPartner: null,
				selectedPartnerId: null,
				selectedAccount: '现金',
				paymentAmount: 0, // 总收款金额
				// 多账户支付方式
				cashAmount: null,
				bankAmount: null,
				wechatAmount: null,
				alipayAmount: null,
				remark: ''
			},
			// --- End State Objects --- 

			emptyText: '购物车里空空如也\n扫描或点击"+"选择商品吧',
			// --- Payment state remains separate ---
			paymentFormData: {
				paymentAmount: 0
			},
			// --- Picker states ---
			showPartnerPicker: false,
			showAccountPicker: false,
			partnerColumns: [],
			accountColumns: [
				{ label: '现金', value: '现金' },
				{ label: '微信', value: '微信' },
				{ label: '支付宝', value: '支付宝' },
				{ label: '银行卡', value: '银行卡' },
				{ label: '其他账户', value: '其他账户' }
			],
			// Keep income/expense types if used elsewhere, otherwise can remove
			incomeType: 'business',
			expenseType: 'business',
		};
	},
	computed: {
		currentState() {
			if (this.currentTab === 0) { // Sales Tab
				if (this.docType === 'sales') {
					return this.salesState;
				} else if (this.docType === 'return') {
					return this.returnState;
				} else { // Includes 'payment' or other unexpected values for Sales
					// Return salesState for payment as well, or handle differently
					return this.salesState; // Or return a specific payment state if needed
				}
			} else if (this.currentTab === 1) { // Purchase Tab
				if (this.docType === 'purchase') {
					return this.purchaseOrderState;
				} else if (this.docType === 'return') {
					return this.purchaseReturnState;
				} else if (this.docType === 'payment') {
					return this.purchasePaymentState;
				} else {
					// Default to purchase order state for purchase tab
					return this.purchaseOrderState;
				}
			} else {
				// Return a default or empty state for other tabs
				return {};
			}
		},
		// Keep other computed properties like formatDateRange, currentApiType etc.
		// Note: currentApiType might need adjustment based on the new state structure
		formatDateRange() { /* ... */ },
		currentApiType() { /* ... might need update ... */ },
		searchPlaceholder() { /* ... */ },
	},
	onShow() {
		// 检查是否有从首页传递过来的目标 tab 索引
		const targetTabIndex = uni.getStorageSync('targetOrderTabIndex');
		if (targetTabIndex !== undefined && targetTabIndex !== null && targetTabIndex !== '') {
			console.log('Detected targetOrderTabIndex:', targetTabIndex);
			// 确保索引是有效的数字
			const index = parseInt(targetTabIndex, 10);
			if (!isNaN(index) && index >= 0 && index < this.tabList.length) {
				// 只有当目标索引和当前索引不同时才切换，避免不必要的重置
				if (this.currentTab !== index) {
					this.currentTab = index;
					this.resetData(); // 切换后重置数据
					this.initPartnerData(); // 切换后初始化伙伴数据
					console.log('Switched to tab index:', index);
				}
			}
			// 清除标记，无论是否成功切换
			uni.removeStorageSync('targetOrderTabIndex');
		}
		// 初始化合作伙伴数据
		this.initPartnerData();
	},
	watch: {
		// 监听总金额变化，更新折后金额和实收金额
		totalAmount: {
			handler(newVal) {
				this.calculateDiscount(true); // Pass true to reset actualAmount
			},
			immediate: true
		},
		// 监听折扣率变化，更新折后金额和实收金额
		discountRate: {
			handler(newVal) {
				this.calculateDiscount(true); // Pass true to reset actualAmount
			},
			immediate: true
		}
	},
	methods: {
		changeTab(e) {
			this.currentTab = e.index;
			// Reset data for the specific tab/state being activated
			this.resetData();
			this.initPartnerData();
		},
		resetData() {
			// Determine which state object to reset based on currentTab and potentially docType
			if (this.currentTab === 0) {
				// Reset both sales and return states if needed, or reset based on docType
				this.salesState = {
					docType: 'sales',
					selectedPartner: null, selectedPartnerId: null, selectedAccount: '现金',
					selectedGoodsCount: 0, selectedGoodsList: [], totalAmount: 0,
					discountRate: 100.00, discountAmount: 0, actualAmount: 0, remark: ''
				};
				this.returnState = {
					docType: 'return',
					selectedPartner: null, selectedPartnerId: null, selectedAccount: '现金',
					selectedGoodsCount: 0, selectedGoodsList: [], totalAmount: 0,
					discountRate: 100.00, discountAmount: 0, actualAmount: 0, remark: ''
				};
				this.docType = 'sales'; // Default to sales when tab 0 is activated
			} else if (this.currentTab === 1) {
				this.purchaseOrderState = {
					docType: 'purchase',
					selectedPartner: '', // 移除默认值，改为空字符串
					selectedPartnerId: null, selectedAccount: '现金',
					selectedGoodsCount: 0, selectedGoodsList: [], totalAmount: 0,
					discountRate: 100.00, discountAmount: 0, actualAmount: 0, remark: ''
				};
				this.docType = 'purchase'; // Default to purchase when tab 1 is activated
			}
			// Reset payment form if needed
			this.paymentFormData.paymentAmount = '';
		},
		changeDocType(type) {
			console.log(`Changing docType for tab ${this.currentTab} to: ${type}`);
			// For purchase tab (currentTab === 1)
			if (this.currentTab === 1) {
				// Update the docType within the purchaseState
				this.purchaseOrderState.docType = type;
				// Update the top-level docType as well, as the template uses it for buttons
				this.docType = type;
			}
			// For sales tab (currentTab === 0)
			else if (this.currentTab === 0) {
				// Update the top-level docType which controls which state/UI is active
				this.docType = type;
				// No need to change salesState/returnState.docType here
			}
			// Reset data maybe needed depending on workflow when changing purchase subtypes?
			// this.resetData(); // Uncomment if needed
			uni.showToast({
				title: `已切换到${this.getDocTypeLabel(type)}`,
				icon: 'none',
				duration: 1000
			});
		},
		getDocTypeLabel(type) {
			const types = {
				'sales': '出货',
				'purchase': '进货',
				'return': '退货',
				'payment': this.currentTab === 0 ? '收款' : '付款'
			};
			return types[type] || '';
		},
		confirmDate(e) {
			const date = new Date(e.value);
			this.selectedDate = date.toISOString().split('T')[0];
			this.currentDate = e.value;
			this.showDatePicker = false;
		},
		initPartnerData() {
			let apiCall;
			let defaultOption;
			let dataMapping;
			let loadingTitle = '';
			let errorTitle = '';

			if (this.currentTab === 0) { // Sales - Customers
				apiCall = api.listCustomer({ pageNum: 1, pageSize: 1000 });
				// defaultOption = { label: '零售客户', value: '零售客户'}; // Or use ID if value is ID
				dataMapping = (item) => ({
					label: item.customerName || '未命名客户',
					value: item.id || item.customerName // Adjust value based on needs (using ID is better for saving)
				});
				loadingTitle = '加载客户...';
				errorTitle = '客户';
				console.log('Fetching customers...');
			} else if (this.currentTab === 1) { // Purchase - Suppliers
				apiCall = api.listSupplier({ pageNum: 1, pageSize: 1000 }); // Use listSupplier
				defaultOption = null; // 移除供应商默认值
				dataMapping = (item) => ({
					label: item.supplierName || '未命名供应商',
					value: item.supplierId, // 确保使用supplierId作为value值
					// 保存完整的供应商对象以便后续使用
					raw: item
				});
				loadingTitle = '加载供应商...';
				errorTitle = '供应商';
				console.log('Fetching suppliers...');
			} else {
				// Handle other tabs or do nothing
				this.partnerColumns = []; // Clear columns for other tabs
				return;
			}

			uni.showLoading({ title: loadingTitle });

			apiCall.then(res => {
				uni.hideLoading();
				console.log(`API response for tab ${this.currentTab}:`, res);
				// **IMPORTANT**: Adjust the check based on the *actual* structure of BOTH APIs
				// Assuming both return { rows: [...] }
				if (res && res.rows && Array.isArray(res.rows)) {
					this.partnerColumns = res.rows.map(dataMapping);
					if (defaultOption) { // 只有存在默认选项时才添加
						this.partnerColumns.unshift(defaultOption);
					}
					console.log(`Formatted partnerColumns for tab ${this.currentTab}:`, this.partnerColumns);
				} else {
					console.error(`Failed to load partners or invalid format for tab ${this.currentTab}`, res);
					uni.showToast({ title: `加载${errorTitle}列表失败`, icon: 'none' });
					this.partnerColumns = defaultOption ? [defaultOption] : []; // 根据是否有默认选项设置
				}
			}).catch(err => {
				uni.hideLoading();
				console.error(`Error fetching partners for tab ${this.currentTab}:`, err);
				uni.showToast({ title: `加载${errorTitle}列表出错`, icon: 'none' });
				this.partnerColumns = defaultOption ? [defaultOption] : []; // 根据是否有默认选项设置
			});
		},
		selectPartner() {
			console.log('selectPartner called. Current partnerColumns:', JSON.stringify(this.partnerColumns));
			if (!this.partnerColumns || this.partnerColumns.length === 0) {
				uni.showToast({ title: '伙伴列表未加载', icon: 'none' });
				return;
			}
			this.$nextTick(() => {
				this.showPartnerPicker = true;
			});
		},
		confirmPartner(e) {
			console.log('confirmPartner event:', JSON.stringify(e));
			let determinedLabel = '选择错误';
			let determinedValue = null;

			// Example using index:
			if (e && e.indexs && Array.isArray(e.indexs) && e.indexs.length > 0) {
				const selectedIndex = e.indexs[0];
				if (selectedIndex >= 0 && selectedIndex < this.partnerColumns.length) {
					const selectedItem = this.partnerColumns[selectedIndex];
					if (selectedItem && selectedItem.label !== undefined && selectedItem.value !== undefined) {
						determinedLabel = selectedItem.label;
						determinedValue = selectedItem.value; // 这里已经是正确的ID
						console.log(`选择的伙伴: ${determinedLabel}, ID: ${determinedValue}`, selectedItem);
					}
				}
			}

			// 根据当前状态更新相应的对象
			if (this.currentTab === 0 && this.docType === 'payment') {
				// 销售收款使用salesPaymentState
				this.salesPaymentState.selectedPartner = determinedLabel;
				this.salesPaymentState.selectedPartnerId = determinedValue;
				console.log(`Updated salesPaymentState partner: ${this.salesPaymentState.selectedPartner}, ID: ${this.salesPaymentState.selectedPartnerId}`);
			} else if (this.currentTab === 1 && this.docType === 'payment') {
				// 进货付款使用purchasePaymentState
				this.purchasePaymentState.selectedPartner = determinedLabel;
				this.purchasePaymentState.selectedPartnerId = determinedValue;
				console.log(`Updated purchasePaymentState partner: ${this.purchasePaymentState.selectedPartner}, ID: ${this.purchasePaymentState.selectedPartnerId}`);
			} else {
				// 其他情况使用currentState
				this.currentState.selectedPartner = determinedLabel;
				this.currentState.selectedPartnerId = determinedValue;
				console.log(`Updated currentState partner: ${this.currentState.selectedPartner}, ID: ${this.currentState.selectedPartnerId}`);
			}

			this.showPartnerPicker = false;
			uni.showToast({
				title: `已选择: ${determinedLabel}`,
				icon: 'none',
				duration: 1500
			});
		},
		selectAccount() {
			this.showAccountPicker = true;
		},
		confirmAccount(e) {
			console.log('confirmAccount event:', JSON.stringify(e));
			let determinedLabel = '选择错误';
			let determinedValue = null;

			// 优先尝试从索引获取
			if (e && e.indexs && Array.isArray(e.indexs) && e.indexs.length > 0) {
				const selectedIndex = e.indexs[0];
				if (selectedIndex >= 0 && selectedIndex < this.accountColumns.length) {
					const selectedItem = this.accountColumns[selectedIndex];
					if (selectedItem && selectedItem.label !== undefined && selectedItem.value !== undefined) {
						determinedLabel = selectedItem.label;
						determinedValue = selectedItem.value;
						console.log(`使用索引获取账户: ${determinedLabel}`);
					}
				}
			}
			// 尝试从值数组获取
			else if (e && e.value && Array.isArray(e.value) && e.value.length > 0) {
				const selectedItem = e.value[0];
				if (typeof selectedItem === 'object' && selectedItem !== null) {
					determinedLabel = selectedItem.label || selectedItem.value || selectedItem;
					determinedValue = selectedItem.value || selectedItem;
					console.log(`使用值对象获取账户: ${determinedLabel}`);
				} else {
					determinedLabel = selectedItem;
					determinedValue = selectedItem;
					console.log(`使用值直接获取账户: ${determinedLabel}`);
				}
			}

			this.currentState.selectedAccount = determinedLabel;
			this.showAccountPicker = false;
			console.log(`已选择账户: ${this.currentState.selectedAccount}`);
		},
		cancelPicker() {
			this.showPartnerPicker = false;
			this.showAccountPicker = false;
		},
		addGoods() {
			uni.navigateTo({
				url: '/pages/goods/select'
			});
		},
		setSelectedGoods(goods, amount) { // This now needs to update currentState
			// 处理新选择的商品，合并而不是替换
			if (goods && goods.length > 0) {
				// 遍历新选择的商品
				goods.forEach(newItem => {
					// 检查是否已存在相同的商品
					const existingItemIndex = this.currentState.selectedGoodsList.findIndex(item => item.id === newItem.id);
					
					if (existingItemIndex >= 0) {
						// 如果已存在，累加数量
						const existingItem = this.currentState.selectedGoodsList[existingItemIndex];
						existingItem.quantity = (parseFloat(existingItem.quantity) || 0) + (parseFloat(newItem.quantity) || 0);
						// 更新该项总价
						existingItem.totalPrice = (existingItem.quantity * parseFloat(existingItem.price)).toFixed(2);
					} else {
						// 如果不存在，添加到列表
						this.currentState.selectedGoodsList.push(newItem);
					}
				});
				
				// 重新计算总数量和总金额
				this.currentState.selectedGoodsCount = this.currentState.selectedGoodsList.length;
				
				// 重新计算总金额
				let totalAmount = 0;
				this.currentState.selectedGoodsList.forEach(item => {
					totalAmount += (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
				});
				this.currentState.totalAmount = Number(totalAmount.toFixed(2));
				
				// 计算折扣金额
				this.calculateDiscount(true);
				
				uni.showToast({
					title: `已添加商品到购物车`,
					icon: 'none',
					duration: 1500
				});
			}
		},
		calculateDiscount(resetActualAmount = false) { // Add parameter
			// Read from and write to the *current* state object
			if (!this.currentState) return; // Guard against missing state

			this.currentState.discountAmount = this.currentState.totalAmount * (this.currentState.discountRate / 100);
			// Only reset actualAmount if explicitly told to (e.g., when discount/total changes)
			// if (resetActualAmount) {
			this.currentState.actualAmount = this.currentState.discountAmount;
			// }
		},
		handleRemarkInput(e) { // Add this method
			if (this.currentState) {
				this.currentState.remark = e.detail.value;
			}
		},
		onActualAmountInput(e) { // Add handler for the new input
			if (this.currentState) {
				const value = parseFloat(e.detail.value);
				// Update actualAmount, allow 0 but not NaN
				this.currentState.actualAmount = isNaN(value) ? 0 : Number(value.toFixed(2));
				console.log(`实收金额手动更新为: ${this.currentState.actualAmount}`);
				// Note: We are NOT recalculating discountRate here based on manual input.
			}
		},
		// ... selectIncomeType, selectExpenseType, getLabels ...

		/**
		 * 重置当前状态对应的表单数据
		 */
		resetCurrentForm() {
			console.log('Resetting form for state:', this.currentTab, this.docType);
			const stateToReset = this.currentState;
			if (stateToReset) {
				// Reset specific fields, keep docType?
				stateToReset.selectedPartner = this.currentTab === 0 ? '请选择' : (this.currentTab === 1 ? '' : '请选择'); // 进货时供应商置空
				stateToReset.selectedPartnerId = null;
				stateToReset.selectedAccount = '现金';
				stateToReset.selectedGoodsList = [];
				stateToReset.selectedGoodsCount = 0;
				stateToReset.totalAmount = 0;
				stateToReset.discountRate = 100.00;
				stateToReset.discountAmount = 0;
				stateToReset.actualAmount = 0;
				stateToReset.remark = '';
				// Also reset payment forms if applicable
				this.paymentFormData.paymentAmount = '';
				if (this.purchasePaymentState) { // Ensure purchasePaymentState exists before resetting
					this.purchasePaymentState.paymentAmount = '';
					this.purchasePaymentState.selectedPartner = ''; // Also reset partner for payment form
					this.purchasePaymentState.selectedPartnerId = null;
					this.purchasePaymentState.remark = '';
				}
				// 重置日期为当前日期
				this.currentDate = Number(new Date());
				this.selectedDate = new Date().toISOString().split('T')[0];

				// 销售或进货的非付款/收款单据，需要重新计算折扣
				if ((this.currentTab === 0 || this.currentTab === 1) && this.docType !== 'payment') {
					this.calculateDiscount();
				}

				console.log('Form reset complete.');
				// uni.showToast({
				// 	title: '已清空表单',
				// 	icon: 'none',
				// 	duration: 1000 // Shorter duration for reset notification
				// });
			} else {
				// Fallback if currentState is somehow unavailable - unlikely but safe
				console.warn('currentState unavailable during reset, performing full resetData.');
				this.resetData(); // Fallback to potentially broader reset
			}
		},

		recordAgain() { // Needs to reset the *current* state
			console.log('Record Again triggered for state:', this.currentTab, this.docType);
			// --- 新逻辑: 调用保存，但不跳转 ---
			this.saveRecord(false); // Pass false to indicate no navigation
		},

		// --- 重构后的保存逻辑 --- 

		/**
		 * 主保存函数，根据当前状态调用不同的处理方法
		 * @param {Boolean} navigateToHome - 保存成功后是否跳转到首页, 默认为 false
		 */
		saveRecord(navigateToHome = false) {
			// 根据不同的标签页和单据类型分发处理
			if (this.currentTab === 0) { // 销售标签页
				if (this.docType === 'payment') {
					this.handleSaveSalesPayment(navigateToHome);
				} else if (this.docType === 'sales' || this.docType === 'return') {
					this.handleSaveSalesDocument(navigateToHome);
				}
			} else if (this.currentTab === 1) { // 进货标签页
				if (this.docType === 'payment') {
					this.handleSavePurchasePayment(navigateToHome);
				} else if (this.docType === 'purchase' || this.docType === 'return') {
					this.handleSavePurchaseDocument(navigateToHome);
				}
			}
			// 其他标签页 (如其他收入/支出) 的保存逻辑可以在这里添加
		},

		/**
		 * 处理保存销售收款
		 * @param {Boolean} navigateToHome - 是否跳转
		 */
		handleSaveSalesPayment(navigateToHome) {
			console.log('处理销售-收款');
			// 使用salesPaymentState代替之前的状态
			const state = this.salesPaymentState;
			
			// 1. 验证客户选择
			if (!state.selectedPartnerId) {
				uni.showToast({ title: '请选择客户', icon: 'none' });
				return;
			}

			// 2. 验证收款金额
			if (state.paymentAmount <= 0) {
				uni.showToast({ title: '请输入有效的收款金额', icon: 'none' });
				return;
			}

			// 3. 显示加载提示
			uni.showLoading({ title: '保存收款...' });

			// 4. 构建提交数据
			const paymentData = {
				customerId: state.selectedPartnerId,
				customerName: state.selectedPartner,
				totalAmount: state.paymentAmount,
				cashAmount: state.cashAmount - 0,
				bankAmount: state.bankAmount - 0,
				wechatAmount: state.wechatAmount - 0,
				alipayAmount: state.alipayAmount - 0,
				remark: state.remark || '',
				type: 'receiveOrder'
			};
			console.log('Saving Sales Payment Data:', paymentData);

			// 5. 调用 API
			api.addSales(paymentData).then(res => {
				this.handleApiResponse(res, '收款保存', navigateToHome);
			}).catch(err => {
				this.handleApiError(err, '收款保存', navigateToHome);
			});
		},

		/**
		 * 处理保存销售单据 (出货/退货)
		 * @param {Boolean} navigateToHome - 是否跳转
		 */
		handleSaveSalesDocument(navigateToHome) {
			console.log(`处理销售-${this.docType}`);
			const state = this.currentState; // 获取 salesState 或 returnState

			// 1. 通用验证
			if (!this.validateOrderData(state, 'sales')) {
				return;
			}

			// 2. 构建提交数据
			const postData = this.buildSalesPayload(state);
			if (!postData) return; // 构建失败
			console.log('准备保存销售单数据:', JSON.stringify(postData, null, 2));
			const type = this.docType === "sales" ? "salesOrder" : "returnOrder";
			// 3. 显示加载提示并调用API
			uni.showLoading({ title: '保存中...' });
			api.addSales({ ...postData, type }).then(res => {
				this.handleApiResponse(res, '销售单保存', navigateToHome);
			}).catch(err => {
				this.handleApiError(err, '销售单保存', navigateToHome);
			});
		},

		/**
		 * 处理保存进货单据 (进货/退货)
		 * @param {Boolean} navigateToHome - 是否跳转
		 */
		handleSavePurchaseDocument(navigateToHome) {
			console.log(`处理进货-${this.docType}`);
			const state = this.currentState; // 获取 purchaseOrderState 或 purchaseReturnState

			// 1. 通用验证
			if (!this.validateOrderData(state, 'purchase')) {
				return;
			}

			// 2. 构建提交数据
			const postData = this.buildPurchasePayload(state);
			if (!postData) return; // 构建失败
			const type = this.docType === "purchase" ? "purchaseOrder" : "returnOrder";
			// 3. 显示加载提示并调用API (请确保 api.addPurchase 是正确的接口)
			uni.showLoading({ title: '保存中...' });
			api.addPurchase({ ...postData, type }).then(res => {
				this.handleApiResponse(res, '进货单保存', navigateToHome);
			}).catch(err => {
				this.handleApiError(err, '进货单保存', navigateToHome);
			});
		},

		/**
		 * 处理保存进货付款 (需要您根据UI实现)
		 * @param {Boolean} navigateToHome - 是否跳转
		 */
		handleSavePurchasePayment(navigateToHome) {
			console.log('处理进货-付款');
			const state = this.purchasePaymentState;

			// 1. 验证供应商选择
			if (!state.selectedPartnerId) {
				uni.showToast({ title: '请选择供应商', icon: 'none' });
				return;
			}

			// 2. 验证付款金额
			if (state.paymentAmount <= 0) {
				uni.showToast({ title: '请输入有效的付款金额', icon: 'none' });
				return;
			}

			uni.showLoading({ title: '保存付款...' });

			// 3. 构建提交数据
			const paymentData = {
				businessDate: this.selectedDate,
				supplierId: state.selectedPartnerId,
				supplierName: state.selectedPartner,
				totalAmount: state.paymentAmount,
				cashAmount: state.cashAmount - 0,
				bankAmount: state.bankAmount - 0,
				wechatAmount: state.wechatAmount - 0,
				alipayAmount: state.alipayAmount - 0,
				remark: state.remark || '',
				type: 'paymentOrder'
			};
			console.log('Saving Purchase Payment Data:', paymentData);

			// 4. 调用 API
			api.addPurchase(paymentData).then(res => {
			    this.handleApiResponse(res, '付款保存', navigateToHome);
			}).catch(err => {
			    this.handleApiError(err, '付款保存', navigateToHome);
			});
		},

		/**
		 * 通用验证函数
		 * @param {Object} state - 当前的状态对象 (salesState, purchaseState等)
		 * @param {String} type - 'sales' 或 'purchase'
		 * @returns {Boolean} - 是否通过验证
		 */
		validateOrderData(state, type) {
			if (type === 'sales' && !state.selectedPartnerId) {
				uni.showToast({ title: '请选择客户', icon: 'none' });
				return false;
			}
			if (type === 'purchase' && !state.selectedPartnerId) {
				uni.showToast({ title: '请选择供应商', icon: 'none' });
				return false;
			}
			if (!state.selectedGoodsList || state.selectedGoodsList.length === 0) {
				uni.showToast({ title: '请先选择商品', icon: 'none' });
				return false;
			}
			return true;
		},

		/**
		 * 构建销售单提交数据
		 * @param {Object} state - salesState 或 returnState
		 * @returns {Object | null} - 构建好的数据对象或null
		 */
		buildSalesPayload(state) {
			const detailItemList = this.buildDetailItemList(state.selectedGoodsList);
			const postData = {
				businessDate: this.selectedDate,
				customerId: state.selectedPartnerId,
				customerName: state.selectedPartner,
				totalAmount: Number(state.totalAmount || 0),
				discount: Number(state.discountRate || 100),
				discountType: 'percent',
				discountedAmount: Number(state.discountAmount || 0),
				actualPayment: Number(state.actualAmount || 0),
				paymentMethod: state.selectedAccount || '现金',
				remark: state.remark || '',
				operation: state.docType,
				salesDetailItemList: detailItemList,
				type: "salesOrder"
			};
			this.calculatePaymentStatus(postData);
			return postData;
		},

		/**
		 * 构建进货单提交数据
		 * @param {Object} state - purchaseOrderState 或 purchaseReturnState
		 * @returns {Object | null} - 构建好的数据对象或null
		 */
		buildPurchasePayload(state) {
			const detailItemList = this.buildDetailItemList(state.selectedGoodsList);
			const postData = {
				businessDate: this.selectedDate,
				supplierId: state.selectedPartnerId,
				supplierName: state.selectedPartner,
				totalAmount: Number(state.totalAmount || 0),
				discount: Number(state.discountRate || 100),
				discountType: 'percent',
				discountedAmount: Number(state.discountAmount || 0),
				actualPayment: Number(state.actualAmount || 0),
				paymentMethod: state.selectedAccount || '现金',
				remark: state.remark || '',
				operation: state.docType,
				purchaseDetailItemList: detailItemList,
				type: "purchaseOrder"
			};
			this.calculatePaymentStatus(postData);
			return postData;
		},

		/**
		 * 构建通用的商品明细列表
		 * @param {Array} goodsList - 选中的商品列表 (来自 state.selectedGoodsList)
		 * @returns {Array} - 符合后端格式的明细列表
		 */
		buildDetailItemList(goodsList) {
			return goodsList.map(item => {
				const quantity = Number(item.quantity || 0);
				const unitPrice = Number(item.price || 0);
				const totalPrice = Number((quantity * unitPrice).toFixed(2));
				return {
					goodsId: item.id,
					goodsName: item.name,
					// goodsCode: item.code || '', 
					// goodsSpec: item.spec || '', 
					quantity: quantity,
					unitPrice: unitPrice,
					totalPrice: totalPrice,
					finalPrice: totalPrice, // 默认等于 total, 如有行折扣需调整
					discount: 100,
					// imageUrl: item.image || '',
				};
			});
		},

		/**
		 * 计算并设置支付状态和欠款
		 * @param {Object} postData - 准备提交的数据对象 (会被直接修改)
		 */
		calculatePaymentStatus(postData) {
			const discountedAmt = postData.discountedAmount;
			const actualPmt = postData.actualPayment;
			if (discountedAmt > 0) {
				if (actualPmt >= discountedAmt) {
					postData.paymentStatus = 'paid';
				} else if (actualPmt > 0 && actualPmt < discountedAmt) {
					postData.paymentStatus = 'partial';
				} else {
					postData.paymentStatus = 'unpaid';
				}
			} else {
				postData.paymentStatus = 'paid'; // 金额为0或负数视为已付清
			}
			postData.pendingPayment = Number((discountedAmt - actualPmt).toFixed(2));
		},

		/**
		 * 处理API成功响应
		 * @param {Object} res - API返回的响应
		 * @param {String} operationDesc - 操作描述 (如: '收款保存')
		 * @param {Boolean} navigateToHome - 是否跳转
		 */
		handleApiResponse(res, operationDesc, navigateToHome) {
			uni.hideLoading();
			// **** 根据您的 API 响应调整成功判断 ****
			if (res&&res.code==200) {
				console.log(111)
				console.log(`${operationDesc} 成功，响应: `, res);
				

				if (navigateToHome) {
					// 跳转到首页
					uni.switchTab({
						url: '/pages/index/index'
					});
					uni.showToast({ title: `${operationDesc}成功` ,icon:'none'});
				}
				// 留在当前页并重置表单
				this.resetCurrentForm();
			} else {
				uni.showToast({ title: `${operationDesc}失败: ${res.msg || '未知错误'}`, icon: 'none' });
				console.error(`${operationDesc}失败，API响应:`, res);
			}
		},

		/**
		 * 处理API错误
		 * @param {Object} err - 捕获到的错误对象
		 * @param {String} operationDesc - 操作描述
		 * @param {Boolean} navigateToHome - (可选) 传递以保持一致性，但通常不用
		 */
		handleApiError(err, operationDesc, navigateToHome = false) { // Added navigateToHome param
			console.log("err",err)
			uni.hideLoading();
			console.error(`${operationDesc}接口调用失败:`, err);
			const errorMsg = err?.msg || err.errMsg || '网络错误';
			uni.showToast({ title: `${operationDesc}失败: ${err|| '网络错误'}`, icon: 'none', duration: 2000 });
		},
		// ... 其他方法 ...
		onDiscountRateInput(e) {
			const value = parseFloat(e.detail.value);
			if (!isNaN(value)) {
				// 限制输入范围在0-100
				const limitedValue = Math.min(Math.max(value, 0), 100);
				this.currentState.discountRate = limitedValue;
				this.calculateDiscount();
				console.log(`折扣率已更新为: ${limitedValue}%`);
			}
		},
		updatePaymentAmount() {
			if (!this.currentState) return;
			
			// 将输入的金额转换为数字，确保非数字值为0
			const cashAmount = parseFloat(this.currentState.cashAmount) || 0;
			const bankAmount = parseFloat(this.currentState.bankAmount) || 0;
			const wechatAmount = parseFloat(this.currentState.wechatAmount) || 0;
			const alipayAmount = parseFloat(this.currentState.alipayAmount) || 0;
			
			// 计算总金额
			const totalAmount = cashAmount + bankAmount + wechatAmount + alipayAmount;
			
			// 更新实际支付金额
			this.currentState.actualAmount = Number(totalAmount.toFixed(2));
			
			// 确定主要支付方式
			if (cashAmount >= bankAmount && cashAmount >= wechatAmount && cashAmount >= alipayAmount && cashAmount > 0) {
				this.currentState.selectedAccount = '现金';
			} else if (bankAmount >= cashAmount && bankAmount >= wechatAmount && bankAmount >= alipayAmount && bankAmount > 0) {
				this.currentState.selectedAccount = '银行存款';
			} else if (wechatAmount >= cashAmount && wechatAmount >= bankAmount && wechatAmount >= alipayAmount && wechatAmount > 0) {
				this.currentState.selectedAccount = '微信';
			} else if (alipayAmount >= cashAmount && alipayAmount >= bankAmount && alipayAmount >= wechatAmount && alipayAmount > 0) {
				this.currentState.selectedAccount = '支付宝';
			}
			
			console.log(`多账户支付总金额: ${this.currentState.actualAmount}, 主要支付方式: ${this.currentState.selectedAccount}`);
		},
		updatePurchasePaymentAmount() {
			// 将输入的金额转换为数字，确保非数字值为0
			const cashAmount = parseFloat(this.purchasePaymentState.cashAmount) || 0;
			const bankAmount = parseFloat(this.purchasePaymentState.bankAmount) || 0;
			const wechatAmount = parseFloat(this.purchasePaymentState.wechatAmount) || 0;
			const alipayAmount = parseFloat(this.purchasePaymentState.alipayAmount) || 0;
			
			// 计算总金额
			const totalAmount = cashAmount + bankAmount + wechatAmount + alipayAmount;
			
			// 更新总支付金额
			this.purchasePaymentState.paymentAmount = Number(totalAmount.toFixed(2));
			
			// 确定主要支付方式
			if (cashAmount >= bankAmount && cashAmount >= wechatAmount && cashAmount >= alipayAmount && cashAmount > 0) {
				this.purchasePaymentState.selectedAccount = '现金';
			} else if (bankAmount >= cashAmount && bankAmount >= wechatAmount && bankAmount >= alipayAmount && bankAmount > 0) {
				this.purchasePaymentState.selectedAccount = '银行存款';
			} else if (wechatAmount >= cashAmount && wechatAmount >= bankAmount && wechatAmount >= alipayAmount && wechatAmount > 0) {
				this.purchasePaymentState.selectedAccount = '微信';
			} else if (alipayAmount >= cashAmount && alipayAmount >= bankAmount && alipayAmount >= wechatAmount && alipayAmount > 0) {
				this.purchasePaymentState.selectedAccount = '支付宝';
			}
			
			console.log(`进货付款总金额: ${this.purchasePaymentState.paymentAmount}, 主要支付方式: ${this.purchasePaymentState.selectedAccount}`);
		},
		updateSalesPaymentAmount() {
			// 将输入的金额转换为数字，确保非数字值为0
			const cashAmount = parseFloat(this.salesPaymentState.cashAmount) || 0;
			const bankAmount = parseFloat(this.salesPaymentState.bankAmount) || 0;
			const wechatAmount = parseFloat(this.salesPaymentState.wechatAmount) || 0;
			const alipayAmount = parseFloat(this.salesPaymentState.alipayAmount) || 0;
			
			// 计算总金额
			const totalAmount = cashAmount + bankAmount + wechatAmount + alipayAmount;
			
			// 更新总收款金额
			this.salesPaymentState.paymentAmount = Number(totalAmount.toFixed(2));
			
			// 确定主要支付方式
			if (cashAmount >= bankAmount && cashAmount >= wechatAmount && cashAmount >= alipayAmount && cashAmount > 0) {
				this.salesPaymentState.selectedAccount = '现金';
			} else if (bankAmount >= cashAmount && bankAmount >= wechatAmount && bankAmount >= alipayAmount && bankAmount > 0) {
				this.salesPaymentState.selectedAccount = '银行存款';
			} else if (wechatAmount >= cashAmount && wechatAmount >= bankAmount && wechatAmount >= alipayAmount && wechatAmount > 0) {
				this.salesPaymentState.selectedAccount = '微信';
			} else if (alipayAmount >= cashAmount && alipayAmount >= bankAmount && alipayAmount >= wechatAmount && alipayAmount > 0) {
				this.salesPaymentState.selectedAccount = '支付宝';
			}
			
			console.log(`销售收款总金额: ${this.salesPaymentState.paymentAmount}, 主要支付方式: ${this.salesPaymentState.selectedAccount}`);
		},
		
		// 处理滑动删除商品
		handleSwipeClick(e, index) {
			console.log('点击了删除按钮', e, index);
			
			// 删除该商品
			this.currentState.selectedGoodsList.splice(index, 1);
			
			// 更新商品计数和总金额
			this.currentState.selectedGoodsCount = this.currentState.selectedGoodsList.length;
			
			// 重新计算总金额
			let totalAmount = 0;
			this.currentState.selectedGoodsList.forEach(item => {
				totalAmount += (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
			});
			this.currentState.totalAmount = Number(totalAmount.toFixed(2));
			
			// 重新计算折扣和实际金额
			this.calculateDiscount(true);
			
			uni.showToast({
				title: '已移除商品',
				icon: 'none',
				duration: 1500
			});
		},
		
		// 增加商品数量
		increaseQuantity(index) {
			const item = this.currentState.selectedGoodsList[index];
			item.quantity = (parseFloat(item.quantity) || 0) + 1;
			this.updateQuantity(index);
		},
		
		// 减少商品数量
		decreaseQuantity(index) {
			const item = this.currentState.selectedGoodsList[index];
			if (item.quantity > 1) {
				item.quantity = (parseFloat(item.quantity) || 0) - 1;
				this.updateQuantity(index);
			}
		},
		
		// 更新商品数量
		updateQuantity(index) {
			const item = this.currentState.selectedGoodsList[index];
			
			// 确保数量为有效数字
			item.quantity = isNaN(parseInt(item.quantity)) ? 1 : parseInt(item.quantity);
			if (item.quantity < 1) item.quantity = 1;
			
			// 更新单项总价
			item.totalPrice = (item.quantity * parseFloat(item.price)).toFixed(2);
			
			// 更新总金额
			let totalAmount = 0;
			this.currentState.selectedGoodsList.forEach(item => {
				totalAmount += (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
			});
			this.currentState.totalAmount = Number(totalAmount.toFixed(2));
			
			// 重新计算折扣和实际金额
			this.calculateDiscount(true);
		}
	}
};
</script>

<style lang="scss" scoped>
.order-container {
	background-color: #f5f7fa;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
}

/* 顶部标题栏 */
.page-header {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	text-align: center;

	.header-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
	}
}

/* 标签页 */
.tabs {
	background-color: #ffffff;
	border-bottom: 1rpx solid #eeeeee;
	display: flex;
	justify-content: center;
}

/* 单据类型按钮 */
.doc-type-buttons {
	display: flex;
	padding: 20rpx;
	background-color: #ffffff;
	justify-content: space-between;

	.doc-button {
		flex: 1;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		font-size: 28rpx;
		color: #333333;
		background-color: #ffffff;
		border: 1px solid #e8e8e8;
		border-radius: 8rpx;
		margin: 0 10rpx;

		&.active {
			color: #39C9BB;
			border-color: #39C9BB;
			background-color: rgba(57, 201, 187, 0.05);
		}

		&:first-child {
			margin-left: 0;
		}

		&:last-child {
			margin-right: 0;
		}
	}
}

/* 信息区域 */
.info-section {
	background-color: #ffffff;
	margin-top: 20rpx;

	.info-item {
		display: flex;
		align-items: center;
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #eeeeee;

		.info-icon {
			margin-right: 15rpx;
		}

		.info-label {
			font-size: 28rpx;
			color: #333333;
			width: 100rpx;
		}

		.info-value {
			flex: 1;
			font-size: 28rpx;
			color: #666666;
			text-align: right;
		}
	}
}

/* 已选择商品区域 */
.selected-goods-section {
	background-color: #ffffff;
	margin-top: 20rpx;

	.selected-goods-header {
		display: flex;
		justify-content: space-between;
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #eeeeee;

		.selected-text {
			font-size: 28rpx;
			color: #333333;
		}

		.total-text {
			font-size: 28rpx;
			color: #333333;
		}
	}

	.selected-goods-list {
		padding: 0;
	}
	
	/deep/ .u-swipe-action-item {
		margin-bottom: 1rpx;
	}

	.selected-goods-item {
		display: flex;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #eeeeee;
		width: 100%;
		box-sizing: border-box;

		.selected-goods-image {
			width: 100rpx;
			height: 100rpx;
			margin-right: 20rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
				background-color: #f5f5f5;
			}
		}

		.selected-goods-info {
			flex: 1;
			display: flex;
			flex-direction: column;

			.selected-goods-name {
				font-size: 28rpx;
				color: #333333;
				margin-bottom: 10rpx;
			}

			.selected-goods-price-row {
				display: flex;
				margin-bottom: 10rpx;

				.selected-goods-price {
					font-size: 24rpx;
					color: #666666;
				}
			}

			.selected-goods-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.quantity-control {
					display: flex;
					align-items: center;

					.btn-minus,
					.btn-plus {
						width: 40rpx;
						height: 40rpx;
						line-height: 36rpx;
						text-align: center;
						font-size: 28rpx;
						color: #666666;
						background-color: #f5f5f5;
						border: 1px solid #e8e8e8;
						border-radius: 50%;
						margin: 0 10rpx;
						cursor: pointer;
					}
					
					.btn-minus {
						color: #999;
					}
					
					.btn-plus {
						color: #3ACBC1;
					}

					.quantity-input {
						width: 60rpx;
						height: 40rpx;
						text-align: center;
						font-size: 28rpx;
						color: #333333;
						border: 1px solid #e8e8e8;
						border-radius: 5rpx;
						margin: 0 5rpx;
					}
				}

				.selected-goods-amount {
					font-size: 24rpx;
					color: #666666;
				}
			}
		}
	}

	.empty-goods {
		padding: 50rpx 0;
	}

	.add-goods-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx 0;
		border-top: 1rpx dashed #eeeeee;
	}
}

/* 结算信息 */
.settlement-section {
	background-color: #ffffff;
	margin-top: 20rpx;

	.settlement-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 30rpx;
		border-bottom: 1rpx solid #eeeeee;

		.settlement-label {
			font-size: 28rpx;
			color: #333333;
		}

		.settlement-value {
			font-size: 28rpx;
			color: #666666;
		}

		.settlement-value-select {
			display: flex;
			align-items: center;

			text {
				font-size: 28rpx;
				color: #666666;
				margin-right: 10rpx;
			}
		}

		&:active {
			background-color: #f8f8f8;
		}
	}
}

/* 备注区域 */
.remark-section {
	background-color: #ffffff;
	margin-top: 20rpx;
	padding: 25rpx 30rpx;

	.remark-btootm {
		height: 150rpx;
	}

	.remark-label {
		font-size: 28rpx;
		color: #333333;
		margin-bottom: 15rpx;
		display: block;
	}

	.remark-input {
		width: 100%;
		height: 150rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 15rpx;
		font-size: 28rpx;
		color: #333333;
	}
}

/* 手机号码 */
.phone-section {
	background-color: #ffffff;
	padding: 25rpx 30rpx;
	margin-top: 20rpx;
	text-align: right;

	.phone-number {
		font-size: 28rpx;
		color: #999999;
	}
}

// 收入和支出类型区域
.income-types,
.expense-types {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;

	.type-row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.type-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 30%;

		.icon-wrapper {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10rpx;

			&.blue {
				background-color: #2979ff;
			}

			&.red {
				background-color: #ff5252;
			}

			&.orange {
				background-color: #ff9800;
			}

			&.yellow {
				background-color: #ffb300;
			}

			&.green {
				background-color: #4caf50;
			}

			&.purple {
				background-color: #9c27b0;
			}
		}

		text {
			font-size: 24rpx;
			color: #666;
		}

		&.active text {
			color: #2979ff;
			font-weight: bold;
		}
	}
}

// 收入和支出头部
.income-header,
.expense-header {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;

	.header-title {
		text-align: center;
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;

		.amount {
			display: block;
			font-size: 40rpx;
			font-weight: 500;
			color: #ff5252;
		}
	}
}

// --- 底部按钮样式 (匹配图片) ---
.footer-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	background-color: #f5f7fa; // Match page background or make transparent if needed
	padding: 20rpx 30rpx; // Add padding around buttons
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05); // Optional top shadow
	z-index: 10;

	.btn-again,
	.btn-save {
		flex: 1;
		height: 80rpx; // Adjust height as needed
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		border-radius: 12rpx; // Rounded corners like image
		margin: 0 10rpx; // Add space between buttons
	}

	.btn-again {
		background-color: #fff;
		color: #3ACBC1; // Image text color
		border: 1rpx solid #E0E0E0; // Light border

		&-hover {
			background-color: #f8f8f8;
		}
	}

	.btn-save {
		background-color: #3ACBC1; // Image background color
		color: #fff;
		border: none; // No border

		&-hover {
			background-color: #31b8ae; // Slightly darker shade for hover
			opacity: 0.9;
		}
	}
}

// --- 结束底部按钮样式 ---

/* Add styles for payment amount section */
.payment-amount-section {
	background-color: #ffffff;
	margin-top: 20rpx;
	padding: 0 20rpx; // Align with form-section padding

	/deep/ .u-form-item {
		min-height: 100rpx;
	}
}

.discount-input-container {
	display: flex;
	align-items: center;
}

.discount-input {
	text-align: right;
	width: 100rpx;
	font-size: 28rpx;
	color: #666666;
	padding: 5rpx;
}

.percent-sign {
	font-size: 28rpx;
	color: #666666;
	margin-left: 5rpx;
}

.actual-amount-input {
	// 新增样式
	text-align: right;
	flex: 1; // 占据剩余空间
	font-size: 28rpx;
	color: #666666;
	padding: 5rpx;
	min-width: 150rpx; // 保证最小宽度
}

.payment-methods {
	display: flex;
	flex-direction: column;
	padding: 14rpx 24rpx;
	
	.payment-method-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0rpx;
		border-bottom: 1rpx solid #eeeeee;
		width: 100%;
		
		.payment-method-icon {
			margin-right: 15rpx;
		}
		
		.payment-method-name {
			flex: 1;
			font-size: 28rpx;
			color: #333333;
			text-align: left;
		}
		
		.payment-method-input {
			width: 200rpx;
			text-align: right;
			font-size: 28rpx;
			color: #666666;
			padding: 5rpx;
		}
	}
}

.payment-total {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 24rpx;
	border-bottom: 1rpx solid #eeeeee;
	
	.payment-total-label {
		font-size: 28rpx;
		color: #333333;
		font-weight: bold;
	}
	
	.payment-total-value {
		font-size: 32rpx;
		color: #ff5252;
		font-weight: bold;
	}
}
</style>